//
//  D3RecordButton.m
//  D3RecordButtonDemo
//
//  Created by bmind on 15/7/28.
//  Copyright (c) 2015年 bmind. All rights reserved.
//

#import "D3RecordButton.h"
#import "RecordHUD.h"

@interface D3RecordButton()<UIAlertViewDelegate>
{
    BOOL isSound;

}

@end
@implementation D3RecordButton

-(void)initRecord:(id<D3RecordDelegate>)delegate maxtime:(int)_maxTime title:(NSString *)_title{
    self.delegate = delegate;
    maxTime = _maxTime;
    title = _title;
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteRecord:) name:@"deleteRecord" object:nil];
    mp3 = [[Mp3Recorder alloc]initWithDelegate:self];
    
    [self addTarget:self action:@selector(startRecord) forControlEvents:UIControlEventTouchDown];
    [self addTarget:self action:@selector(stopRecord) forControlEvents:UIControlEventTouchUpInside];
    [self addTarget:self action:@selector(cancelRecord) forControlEvents:UIControlEventTouchUpOutside | UIControlEventTouchCancel];
    [self addTarget:self action:@selector(RemindDragExit:) forControlEvents:UIControlEventTouchDragExit];
    [self addTarget:self action:@selector(RemindDragEnter:) forControlEvents:UIControlEventTouchDragEnter];
}
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)initRecord:(id<D3RecordDelegate>)delegate maxtime:(int)_maxTime{
    [self initRecord:delegate maxtime:_maxTime title:nil];
}
- (void)deleteRecord:(NSNotification*)noti
{
    isSound=NO;
}

//开始录音
-(void)startRecord{

    if (isSound==YES) {
        [CClass showMessage:@"最多上传1段语音"];

    }else
    {

        
       // if ([[UIDevice currentDevice] systemVersion].floatValue>=7.0&&[[UIDevice currentDevice] systemVersion].floatValue<10.0)
       // {
            
            //第一次调用这个方法的时候，系统会提示用户让他同意你的app获取麦克风的数据
            // 其他时候调用方法的时候，则不会提醒用户
            // 而会传递之前的值来要求用户同意
            [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
                if (granted) {
                    // 用户同意获取数据
                    //授权成功，执行后续操作
                    [mp3 startRecord];
                    [RecordHUD show];
                    [self setHUDTitle];
                } else {
                    // 可以显示一个提示框告诉用户这个app没有得到允许？

                    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用麦克风" message:@"请在iPhone的""设置-隐私-相机""中允许访问麦克风" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
                    [alert show];


                }
            }];

          //  AVAudioSession *audioSession = [AVAudioSession sharedInstance];
           // if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
               // [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                    // if (granted) {
                        //授权成功，执行后续操作
                       //  [mp3 startRecord];
                      //   [RecordHUD show];
                        // [self setHUDTitle];
                   //  } else {
                     //    [CClass showMessage:@"录音访问受限"];
                    // }
                // }];
             //}
        //}else if ([[UIDevice currentDevice] systemVersion].floatValue>=10.0)
        //{
            
       // }
        
       
    }
   
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { // 去设置界面，开启相机访问权限
        if (iOS8Later) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=Photos"]];
        }
    }
}
-(BOOL)canRecord

{
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                if (granted) {
                    bCanRecord = YES;
                }
                else {
                    bCanRecord = NO;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[[UIAlertView alloc] initWithTitle:nil
                                                     message:@"app需要访问您的麦克风。\n请启用麦克风-设置/隐私/麦克风"
                                                    delegate:nil
                                           cancelButtonTitle:@"关闭"
                                           otherButtonTitles:nil] show];
                    });
                }
            }];
        }
    }
    
    return bCanRecord;
}
//正常停止录音，开始转换数据
-(void)stopRecord{
    [mp3 stopRecord];
    [RecordHUD dismiss];

}

//取消录音
-(void)cancelRecord{
    [mp3 cancelRecord];
    [RecordHUD dismiss];
    [RecordHUD setTitle:@"已取消录音"];
    isSound=NO;

}

//离开按钮范围
- (void)RemindDragExit:(UIButton *)button
{
    [RecordHUD setTitle:@"松手取消录音"];
    if ([_delegate respondsToSelector:@selector(dragExit)]) {
        [_delegate dragExit];
    }
}

//进入按钮范围
- (void)RemindDragEnter:(UIButton *)button
{
    [self setHUDTitle];
    if ([_delegate respondsToSelector:@selector(dragEnter)]) {
        [_delegate dragEnter];
    }
}

-(void)setHUDTitle{
    if (title != nil) {
        [RecordHUD setTitle:title];
    }
    else{
        [RecordHUD setTitle:@"离开按钮取消录音"];
    }
}


#pragma mark Mp3RecordDelegate
-(void)beginConvert{
}

//录音失败
- (void)failRecord
{
}


//回调录音资料
- (void)endConvertWithData:(NSData *)voiceData
{
    [RecordHUD setTitle:@"录音成功"];
    //成功之后把变成 yes,  发通知进行显示语音
    isSound=YES;
    
    //创建通知 录音通知
    NSNotification *notification =[NSNotification notificationWithName:@"startRecord" object:nil userInfo:nil];
    //通过通知中心发送通知
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    if ([_delegate respondsToSelector:@selector(endRecord:)]) {
        [_delegate endRecord:voiceData];
      
    }
}

-(void)recording:(float)recordTime volume:(float)volume{
    if (recordTime>=10) {
        [self stopRecord];
    }
    [RecordHUD setImage:[NSString stringWithFormat:@"mic_%.0f.png",volume*10 > 5 ? 5 : volume*10]];
    [RecordHUD setTimeTitle:[NSString stringWithFormat:@"录音: %.0f\"",recordTime]];
}
@end
